//
//  OverTimeViewController.m
//  OA
//
//  Created by yy on 17/7/5.
//  Copyright © 2017年 yy. All rights reserved.
//

#import "OverTimeViewController.h"
#import "csCell.h"
#import "csAddCell.h"
#import "shCell.h"
#import "shAddCell.h"
@interface OverTimeViewController ()<TimeChouseDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *backView;


@property (weak, nonatomic) IBOutlet UIButton *beginTiemBtn;
@property (weak, nonatomic) IBOutlet UIButton *endTiemBtn;
@property (weak, nonatomic) IBOutlet UILabel *beginTimeL;
@property (weak, nonatomic) IBOutlet UILabel *endTimeL;

@property (weak, nonatomic) IBOutlet UILabel *textFieldTitleL;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UILabel *contentTiTleL;
@property (weak, nonatomic) IBOutlet UITextView *contentTextView;
@property (weak, nonatomic) IBOutlet UIButton *sendBtn;
@property (weak, nonatomic) IBOutlet UIButton *auditBtn;
@property (weak, nonatomic) IBOutlet UIButton *isHolidayBtn;
@property (weak, nonatomic) IBOutlet UIButton *notHolidayBtn;

@property (weak, nonatomic) IBOutlet UILabel *timeTitleL;
@property (weak, nonatomic) IBOutlet UITextField *timeTextField;
@property (nonatomic,strong)BasisChooseTimeView *viewOfTime;
@property (nonatomic ,strong) NSMutableArray *csArr;
@property (nonatomic ,strong) NSMutableArray *shArr;
@property (weak, nonatomic) IBOutlet UICollectionView *csCollectionView;
@property (weak, nonatomic) IBOutlet UICollectionView *shCollectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *isHolidayLayoutConstraint;
@property (weak, nonatomic) IBOutlet UIView *isHolidayView;

@end

@implementation OverTimeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initOfDataSouce];
    [self initializeUserInterface];
    self.csArr = @[].mutableCopy;
    self.shArr = @[].mutableCopy;
}
- (void)initOfDataSouce{
    if (_isFieldType == NO) {
        self.title = @"加班申请";
        _textFieldTitleL.text = @"加班原因";
        _textField.placeholder = @"请输入加班原因";
        _contentTiTleL.text = @"加班内容";
        _timeTitleL.text = @"加班时间";
        
        
    }else{
        self.title = @"外勤申请";
    }
}
//_isHolidayView
- (void)initializeUserInterface{
    _isHolidayBtn.selected = NO;
    _notHolidayBtn.selected = !_isHolidayBtn.selected;
    
    if (_isFieldType == YES) {
        _isHolidayLayoutConstraint.constant = 0;
        _isHolidayView.hidden = YES;
        
    }else{
        _isHolidayLayoutConstraint.constant = 50;
        _isHolidayView.hidden = NO;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (IBAction)chooseTimeAction:(UIButton *)sender {//130 131
    [self.view endEditing:YES];
    
    [self.view addSubview:self.viewOfTime];
    _viewOfTime.tag = sender.tag;
}

- (IBAction)isHoliday:(UIButton *)sender {
    _isHolidayBtn.selected = YES;
    _notHolidayBtn.selected = !_isHolidayBtn.selected;
}
- (IBAction)notHoliday:(UIButton *)sender {
    _isHolidayBtn.selected = NO;
    _notHolidayBtn.selected = !_isHolidayBtn.selected;
    
}

- (IBAction)approverAction:(UIButton *)sender {
    NSLog(@"审批人");
}
- (IBAction)sendToAction:(UIButton *)sender {
    NSLog(@"抄送人");
}
- (IBAction)okBtnAction:(UIButton *)sender {
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *num = [self.timeTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if (self.beginTimeL.text.length == 0) {
        [MBProgressHUD showError:@"请选择开始时间"];
        return;
    }
    if (self.endTimeL.text.length == 0) {
        [MBProgressHUD showError:@"请选择结束时间"];
        return;
    }
    if (self.timeTextField.text.length == 0) {
        if (self.isFieldType) {
            [MBProgressHUD showError:@"请填写外勤时长"];
        } else {
            [MBProgressHUD showError:@"请填写加班时长"];
        }
       
        return;
    }
    if (self.textField.text.length == 0) {
        if (self.isFieldType) {
            [MBProgressHUD showError:@"请填写外勤地点"];
        } else {
            [MBProgressHUD showError:@"请填写加班原因"];
        }
        
        return;
    }
    
    if (self.isHolidayBtn.selected == NO && self.notHolidayBtn.selected == NO) {
        [MBProgressHUD showError:@"请选择是否节假日"];
        return;
    }
    if (self.contentTextView.text.length == 0) {
        if (self.isFieldType) {
            [MBProgressHUD showError:@"请填写外勤目的"];
        } else {
            [MBProgressHUD showError:@"请填写加班内容"];
        }
        return;
    }
//    if (self.csArr.count == 0) {
//        [MBProgressHUD showError:@"请选择抄送人"];
//        return;
//    }
    if (self.shArr.count == 0) {
        [MBProgressHUD showError:@"请选择审核人"];
        return;
    }
    if (!([self.beginTimeL.text compare:self.endTimeL.text] < 0)) {
        [MBProgressHUD showError:@"结束时间必须大于开始时间"];
        return;
    }
    if (![[self.beginTimeL.text substringToIndex:10] isEqualToString:[self.endTimeL.text substringToIndex:10]]) {
        [MBProgressHUD showError:@"时间不能超过一天"];
        return;
    }
    if (num.length > 0) {
        [MBProgressHUD showError:@"请输入正确的时长"];
        return;
    }
    NSMutableString *csId = @"".mutableCopy;
    NSMutableString *csName = @"".mutableCopy;
    NSMutableString *shId = @"".mutableCopy;
    NSMutableString *shName = @"".mutableCopy;
    for (NSDictionary *dic in self.csArr){
        [csId appendFormat:@"%@",dic[@"id"]];
        [csId appendFormat:@";"];
        [csName appendFormat:@"%@",dic[@"name"]];
        [csName appendFormat:@";"];
    }
    for (NSDictionary *dic in self.shArr){
        [shId appendFormat:@"%@",dic[@"id"]];
//        [shId appendFormat:@";"];
        [shName appendFormat:@"%@",dic[@"name"]];
//        [shName appendFormat:@";"];
    }
    
    [dic setObject:self.beginTimeL.text forKey:@"begintime"];
    [dic setObject:self.endTimeL.text forKey:@"endtime"];
    [dic setObject:@"小时" forKey:@"numname"];
    [dic setObject:self.timeTextField.text forKey:@"num"];
    [dic setObject:shId forKey:@"auditors"];
    [dic setObject:shName forKey:@"auditorsName"];
    [dic setObject:csId forKey:@"lookers"];
    [dic setObject:csName forKey:@"lookersName"];
    if (!self.isFieldType) { // 加班
        if (self.isHolidayBtn.selected) {
            [dic setObject:@"是" forKey:@"isholiday"];
        } else {
            [dic setObject:@"否" forKey:@"isholiday"];
        }
        [dic setObject:self.contentTextView.text forKey:@"content"];
        NSDate *date = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设置格式：zzz表示时区
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        //NSDate转NSString
        NSString *currentDateString = [dateFormatter stringFromDate:date];
        [dic setObject:currentDateString forKey:@"datenumber"];
        [dic setObject:self.textField.text forKey:@"reason"];
    } else {
        [dic setObject:self.contentTextView.text forKey:@"reason"];
        [dic setObject:self.textField.text forKey:@"address"];
    }
    
    
    Y_Wait
    [[ToolOfNetWork sharedTools] YrequestURL:self.isFieldType ? oa_insertAttendanceAuditByEgress:oa_insertAttendanceAuditByOvertime withParams:dic.mutableCopy finished:^(id responsObject, NSError *error) {
        Y_Hide
        if (_Success) {
            [MBProgressHUD showSuccess:@"申请成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        } else {
            [MBProgressHUD showError:responsObject[@"message"]];
        }
        NSLog(@"%@",[[responsObject description]kdtk_stringByReplaceingUnicode]);
        NSLog(@"%@",error.localizedDescription);
    }];
    
}

#pragma mark --- UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.csCollectionView) {
        return self.csArr.count + 1;
    } else {
        return self.shArr.count + 1;
    }
    
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if(collectionView == self.csCollectionView) {
        if (indexPath.row < self.csArr.count) {
            csCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"csCell" forIndexPath:indexPath];
            cell.image.backgroundColor = [UIColor getColorWithHexString:@"FEA100"];
            cell.image.layer.cornerRadius = 20;
            cell.image.clipsToBounds = YES;
            
            NSString *nameStr = self.csArr[indexPath.row][@"name"];
            
            if (nameStr.length <3) {
                cell.name.text = nameStr;
            } else {
                cell.name.text = [nameStr substringWithRange:NSMakeRange(nameStr.length - 2, 2)];
            }
            return cell;
        } else {
            csAddCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"csAddCell" forIndexPath:indexPath];
            return cell;
        }
    } else {
        if (indexPath.row < self.shArr.count) {
            shCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"shCell" forIndexPath:indexPath];
            cell.image.backgroundColor = [UIColor getColorWithHexString:@"FEA100"];
            cell.image.layer.cornerRadius = 20;
            cell.image.clipsToBounds = YES;
            
            NSString *nameStr = self.shArr[indexPath.row][@"name"];
            
            if (nameStr.length <3) {
                cell.name.text = nameStr;
            } else {
                cell.name.text = [nameStr substringWithRange:NSMakeRange(nameStr.length - 2, 2)];
            }
            return cell;
        } else {
            shAddCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"shAddCell" forIndexPath:indexPath];
            return cell;
        }
    }
    
}

#pragma mark --- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.csCollectionView) {
        if (indexPath.row < self.csArr.count) {
            [self.csArr removeObjectAtIndex:indexPath.row];
            [self.csCollectionView reloadData];
        } else {
            BumenChoiceViewController *vc = VCInSB(@"BumenChoiceViewController", @"BumenViewController");
            vc.type = @"1";
            vc.vc = self;
            vc.csshArr = self.csArr;
            vc.back = ^() {
                if ([ShareUserInfo sharedUserInfo].csArr.count > 0) {
                    [self.csArr removeAllObjects];
                    [self.csArr addObjectsFromArray:    [ShareUserInfo sharedUserInfo].csArr];
                    [self.csCollectionView reloadData];
                }
            };
            [self.navigationController pushViewController:vc animated:YES];
            
        }
    } else {
        if (indexPath.row < self.shArr.count) {
            [self.shArr removeObjectAtIndex:indexPath.row];
            [self.shCollectionView reloadData];
        } else {
            BumenChoiceViewController *vc = VCInSB(@"BumenChoiceViewController", @"BumenViewController");
            vc.type = @"1";
            vc.vc = self;
            vc.csshArr = self.shArr;
            vc.back = ^() {
                if ([ShareUserInfo sharedUserInfo].csArr.count > 0) {
                    [self.shArr removeAllObjects];
                    [self.shArr addObject:[ShareUserInfo sharedUserInfo].csArr[0]];
                    [self.shCollectionView reloadData];
                }
            };
            [self.navigationController pushViewController:vc animated:YES];
            
        }
    }
    
    
    
}
#pragma mark —————— time
- (BasisChooseTimeView *)viewOfTime{
    if (!_viewOfTime) {
        
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"BasisChooseTimeView" owner:self options:nil];
        _viewOfTime = (BasisChooseTimeView *)[nib objectAtIndex:0];
        _viewOfTime.frame = CGRectMake(30, 30, Y_mainW-60, 280);
        _viewOfTime.center = self.view.center;
        _viewOfTime.layer.cornerRadius = 20;
        _viewOfTime.layer.borderWidth = 0.2;
        _viewOfTime.delegateOfTime = self;
        _viewOfTime.isPrecision = YES;
    }
    return _viewOfTime;
}

- (NSString *)dateOfDidSelect:(NSString *)str{
    if (_viewOfTime.tag == 130) {
        _beginTimeL.text = str;
    }else{
        _endTimeL.text = str;
    }
    [_viewOfTime removeFromSuperview];
    return str;
}
- (void)removeBasisChooseTimeView{
    [_viewOfTime removeFromSuperview];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
     [_viewOfTime removeFromSuperview];
}

@end
